package com.example.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dto.DishFlavorsDTO;
import com.example.entity.DishFlavorsEntity;
import com.example.mybatis.service.impl.CrudServiceImpl;
import com.example.dao.FlavorsDao;
import com.example.dto.ZyFlavorsDTO;
import com.example.entity.FlavorsEntity;
import com.example.service.FlavorsService;
import com.example.utils.ConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 口味表
 *
 * @author yyyyjinying 1020066395@qq.com
 * @since 1.0-SNAPSHOT 2025-04-29
 */
@Service
public class FlavorsServiceImpl extends CrudServiceImpl<FlavorsDao, FlavorsEntity, ZyFlavorsDTO> implements FlavorsService {

    @Override
    public QueryWrapper<FlavorsEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<FlavorsEntity> wrapper = new QueryWrapper<>();


        return wrapper;
    }

    @Override
    public void save(ZyFlavorsDTO dto) {
        FlavorsEntity entity = ConvertUtils.sourceToTarget(dto, FlavorsEntity.class);
        entity.setFlavorId(snowflake.nextId()); // 主键id可能有错误
        baseDao.insert(entity);
    }

    @Override
    public List<DishFlavorsDTO> flavorsByDishId(Long dishId) {
        List<DishFlavorsEntity> dishFlavorsEntities = baseDao.flavorsByDishId(dishId, null);
        return ConvertUtils.sourceToTarget(dishFlavorsEntities, DishFlavorsDTO.class);
    }

    @Override
    public void saveAndUpdateFlavor(Long dishId, List<DishFlavorsDTO> flavorsList) {
        if (CollectionUtils.isEmpty(flavorsList)){
            return;
        }

        // 根据插入的数据流，筛选出已选中的标签，映射为DishTagsEntity对象集合
        List<DishFlavorsEntity> DishFlavorsEntityCollect = flavorsList.stream().map(item -> {
            DishFlavorsEntity dishFlavorsEntity = new DishFlavorsEntity();
            dishFlavorsEntity.setDishId(dishId);
            dishFlavorsEntity.setFlavorId(item.getFlavorId());
            dishFlavorsEntity.setFlavorValue(item.getFlavorValue());
            return dishFlavorsEntity;
        }).collect(Collectors.toList());

        baseDao.deleteDishFlavoersRelation(ListUtil.of(dishId), null);
        baseDao.batchInsertDishFlavorsRelation(DishFlavorsEntityCollect);
    }


}